package com.my.company.base.dao.impl;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.my.company.base.dao.BaseDao;


@SuppressWarnings("rawtypes")
public class BaseDaoImpl<T> implements BaseDao<T> {
	private Class clazz;
	public BaseDaoImpl() {
		ParameterizedType type = (ParameterizedType) this.getClass()
				.getGenericSuperclass();
		clazz = (Class) type.getActualTypeArguments()[0];
	}

	@Resource
	private SessionFactory sf;
	public void saveEntity(T t) {
		sf.getCurrentSession().save(t);
	}

	public void updateEntity(T t) {
		sf.getCurrentSession().update(t);
	}

	public void deleteEntity(T t) {
		sf.getCurrentSession().delete(t);
	}

	public void saveOrUpdateEntity(T t) {
		sf.getCurrentSession().saveOrUpdate(t);
	}

	public void batchEntityByHQL(String hql, Object... objects) {
		Session s = sf.getCurrentSession();
		Query q = s.createQuery(hql);
		for (int i = 0; i < objects.length; i++) {
			q.setParameter(i, objects[i]);
		}
		q.executeUpdate();
	}

	@SuppressWarnings("unchecked")
	public T getEntity(String id) {
		return (T) sf.getCurrentSession().get(clazz, id);
	}

	@SuppressWarnings("unchecked")
	public T loadEntity(String id) {
		return (T) sf.getCurrentSession().load(clazz, id);

	}
	@SuppressWarnings("unchecked")
	public T getEntity(Integer id) {
		return (T) sf.getCurrentSession().get(clazz, id);
	}

	@SuppressWarnings("unchecked")
	public T loadEntity(Integer id) {
		return (T) sf.getCurrentSession().load(clazz, id);

	}

	@SuppressWarnings("unchecked")
	public List<T> findEntityByHQL(String hql, Object... objects) {
		Session s = sf.getCurrentSession();
		Query q = s.createQuery(hql);
		for (int i = 0; i < objects.length; i++) {
			q.setParameter(i, objects[i]);
		}
		return q.list();
	}

	@SuppressWarnings("unchecked")
	public List<T> getListForPage(String hql, int offset, int length) {
		   Query query = sf.getCurrentSession().createQuery(hql);
		     query.setFirstResult(offset);
		     query.setMaxResults(length);
		     return  query.list();
	}
	
}
